package ltd.newbee.mall.web;

import lombok.extern.slf4j.Slf4j;
import ltd.newbee.mall.common.R;
import ltd.newbee.mall.config.PaypalConfig;
import ltd.newbee.mall.controller.vo.PaypalVo;
import ltd.newbee.mall.service.NewBeeMallOrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.IOException;

/**
 * @author pyw
 * @date 2020-07-21 16:52
 * @description
 **/
@Controller
@Slf4j
public class PayWebController {


    @Autowired
    PaypalConfig paypalConfig;

    @Autowired
    NewBeeMallOrderService orderService;

    /*@GetMapping(value = "/payOrder", produces = "text/html")
    @ResponseBody
    public String payOrder(@RequestParam("orderSn") String orderSn) throws AlipayApiException {
        PayVo payVo = orderService.getOrderPay(orderSn);
        String pay = alipayTemplate.pay(payVo);
        System.out.println(pay);
        return pay;
    }*/

    @GetMapping(value = "/payOrderByPaypal")
    @ResponseBody
    public R payOrderByPaypal(@RequestParam("orderNo") String orderNo) {
        PaypalVo paypalVo = new PaypalVo();
        try {
            paypalVo = orderService.getOrderPayByPaypal(orderNo);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return StringUtils.isEmpty(paypalVo.getAuthorizeUrl()) ? R.error() : R.ok().put("data", paypalVo.getAuthorizeUrl());
    }

    @GetMapping(value = "/paypal/cancel")
    public String cancelPay() {
        log.info("付款失败");
        return null;
    }


    @GetMapping(value = "/paypal/success")
    public String successPay(@RequestParam("token") String token, @RequestParam("PayerID")String PayerID) throws IOException {
        String orderNo = orderService.orderCaptureOrder(token);
        if (orderNo != null&&orderNo != "") {
            System.out.println("授权成功");
            //return R.ok();
            return "redirect:/orders/"+orderNo;
        }
        return "error/error_5xx";
    }
}
